<?php

namespace App\Http\Controllers\Admin;

use App\Models\Link;

class LinkController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function index(){

        if ($this->isOnSubmit()) {
            $delete = $this->request->post('delete');
            if ($delete && is_array($delete)){
                foreach ($delete as $id){
                    Link::where('id', $id)->delete();
                }
            }

            $itemlist = $this->request->post('itemlist');
            if ($itemlist && is_array($itemlist)) {
                foreach ($itemlist as $id=>$item){
                    if ($item['title']) {
                        if ($id > 0){
                            Link::where('id', $id)->update($item);
                        }else {
                            Link::insert($item);
                        }
                    }
                }
            }
            return $this->messager()->message(trans('sysmessage.info save success'))->render();
        }else {

            $this->assign(['categorylist'=>Link::with('links')->where('type', 'category')->orderBy('displayorder')->get()]);

            return $this->view('admin.common.link');
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function setimage(){
        $id = $this->request->input('id');
        $image = $this->request->input('image');
        if ($id && $image){
            Link::where('id', $id)->update(['image'=>$image]);
        }
        return ajaxReturn();
    }
}
